<?php
header("Content-Type:text/html;charset=utf-8");

//判断用户是否登录
// $_SESSION['s_username'] = null;
session_start();
$sessions = empty($_SESSION['s_username']) ? '' : $_SESSION['s_username'];
if ($sessions == '') {
  //用户名或密码不存在，弹出‘该用户不存在’
  echo "<script>alert('请先登录账户！');window.location.href='login.php'</script>";
  exit();
}
//引入连接数据库文件 require
require './lib/init.php';

//sql语句 查询栏目下拉框
$sql = 'select * from cat';
$cat = mGetAll($sql);
if (!$_POST) {
  require ROOT . '/view/admin/artadd.html';
  exit();
}
$title = trim($_POST['title']);
$cat_id = trim($_POST['cat_id']);
$content = trim($_POST['content']);
if (empty($title)) {
  echo "标题不能为空";
  exit();
}
if (empty($cat_id)) {
  echo "栏目不能为空";
  exit();
}
if (empty($content)) {
  echo "内容不能不能为空";
  exit();
}
$sql = "select * from art where title='$title'";
$res = mQuery($sql);
if (!$res) {
  //记录日志
  echo mysqli_error($conn);
  exit();
}
//获取查询结果
$row = mGetRow($sql);
if ($row) {
  echo "该标题已存在！";
  exit();
}
//栏目
// $sql = "insert into art(title,cat_id,content) values('$title',$cat_id,'$content')";
// $res = mQuery($sql);
$res = mExec('art', $_POST);

//通过获取栏目id,使用修改语句，给这个栏目的<num></num>
$sql = "select num from cat where cat_id=$cat_id";
$row = mGetRow($sql);
$num = $row['num'] + 1;
$cat = array('num' => $num);
$rescat = mExec('cat', $cat, 'update', "cat_id=$cat_id");

if ($res) {
  //记录日志
  echo "<script>alert('添加成功！');window.location.href='artlist.php'</script>";
}
